﻿///<summary>
         
///</summary>

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

//Common reference
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Xml.Serialization;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Reflection;
using MySql.Data.MySqlClient;
using static MDLoader.Form1;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using System.Data.SqlClient;
using System.Data.SqlTypes;

namespace MDLoader
{

    public partial class SetupForm : Form
    {
        public static Config cfg;
        private MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
        private MySqlConnection connection;
        /// <summary>
        /// 从config.xml中加载配置到Config对象
        /// </summary>
        public SetupForm()
        {

            
            cfg =Config.LoadfromFile(Application.StartupPath+"\\config.xml");
            if (cfg == null)
            {   if(gStr.MyName != "")
                {
                    cfg = new Config();
                    cfg.ServerAddress = "ftp.miuser.net";
                    cfg.Port = 21;
                    
                }
               
                
            }
            else
            {
                if(gStr.MyName !="")
                {
                    string strcon = "data source=localhost;database=md;user id=root;password=123456;pooling=true;charset=utf8;";
                    MySqlConnection con = new MySqlConnection(strcon);
                    //2. 打开数据库
                    con.Open();
                    //3. sql语句
                    string sqlSel = "select * from ftp_config where UserName='" + gStr.MyName + "'";
                    MySqlCommand com = new MySqlCommand(sqlSel, con);
                    // Execute the SQL query and retrieve the result
                    MySqlDataReader reader = com.ExecuteReader();

                    if (reader.HasRows)
                    {
                        string ids = "";
                        string httpUrls = "";
                        string passwords = "";
                        string ServerAddres = "";
                        string UserNames = "";
                        int ports = 21;
                        while (reader.Read())
                        {

                            ids += reader.GetInt32("id").ToString();
                            httpUrls += reader.GetString("httpUrl");
                            passwords += reader.GetString("password");
                            ServerAddres += reader.GetString("ServerAddre");
                            UserNames += reader.GetString("UserName");
                            ports = reader.GetInt32("port");
                        }
                        cfg.Port = ports;
                        cfg.UserName = UserNames;
                        cfg.Password = passwords;
                        cfg.HttpUrlHead = httpUrls;
                        cfg.ServerAddress = ServerAddres;
                        //MessageBox.Show(httpUrls);
                    }
                    else
                    {
                        MessageBox.Show("您未配置ftp服务器");
                    }
                    reader.Close();
                    con.Close();
                }
                else
                {
                    MessageBox.Show("未登录，暂无ftp服务器配置信息");
                }
               
            }
            InitializeComponent();
        }

        private void SetupForm_Load(object sender, EventArgs e)
        {
            prg_config.SelectedObject = cfg;
            MoveSplitterTo(prg_config, 160);
        }
        /// <summary>
        /// 调整栏目宽度，由于这个方法本身的propertygrid没有公有方法支持，所以需要用反射技术调用私有方法实现
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="x"></param>
        public void MoveSplitterTo(PropertyGrid grid, int x)
        {
            // HEALTH WARNING: reflection can be brittle...
            FieldInfo field = typeof(PropertyGrid)
                .GetField("gridView",
                    BindingFlags.NonPublic | BindingFlags.Instance);
            field.FieldType
                .GetMethod("MoveSplitterTo",
                    BindingFlags.NonPublic | BindingFlags.Instance)
                .Invoke(field.GetValue(grid), new object[] { x });
        }
        private void btn_save_Click(object sender, EventArgs e)
        {
            //cfg.SavetoFile(Application.StartupPath + "\\config.xml");
            string strcon = "data source=localhost;database=md;user id=root;password=123456;pooling=true;charset=utf8;";
            MySqlConnection con = new MySqlConnection(strcon);

            // Open the database connection
            con.Open();

            // SQL query to check if the UserName exists in the ftp_config table
            string sqlSel = "SELECT COUNT(*) FROM ftp_config WHERE UserName = @UserName";
            MySqlCommand com = new MySqlCommand(sqlSel, con);
            com.Parameters.AddWithValue("@UserName", gStr.MyName);

            // Execute the SQL query and retrieve the result
            int count = Convert.ToInt32(com.ExecuteScalar());

            if (count > 0)
            {
                // UserName already exists, update the corresponding record
                string sqlUpdate = "UPDATE ftp_config SET httpUrl = @httpUrl, ServerAddre = @ServerAdder, password = @password, port = @port WHERE UserName = @UserName";
                MySqlCommand comUpdate = new MySqlCommand(sqlUpdate, con);
                comUpdate.Parameters.AddWithValue("@httpUrl", cfg.HttpUrlHead);
                comUpdate.Parameters.AddWithValue("@ServerAdder", cfg.ServerAddress);
                comUpdate.Parameters.AddWithValue("@password", cfg.Password);
                comUpdate.Parameters.AddWithValue("@port", cfg.Port);
                comUpdate.Parameters.AddWithValue("@UserName", gStr.MyName);
                comUpdate.ExecuteNonQuery();
            }
            else
            {
                // UserName doesn't exist, add a new record
                string sqlInsert = "INSERT INTO ftp_config (httpUrl, ServerAddre, password, UserName, port) VALUES (@httpUrl, @ServerAdder, @password, @UserName, @port)";
                MySqlCommand comInsert = new MySqlCommand(sqlInsert, con);
                comInsert.Parameters.AddWithValue("@httpUrl", cfg.HttpUrlHead);
                comInsert.Parameters.AddWithValue("@ServerAdder", cfg.ServerAddress);
                comInsert.Parameters.AddWithValue("@password", cfg.Password);
                comInsert.Parameters.AddWithValue("@port", cfg.Port);
                comInsert.Parameters.AddWithValue("@UserName", gStr.MyName);
                comInsert.ExecuteNonQuery();
            }

            // Close the reader and the database connection
            con.Close();
            Application.Restart();

        }

        private void SetupForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Reload parameter form in case cancel the cange
           cfg=Config.LoadfromFile(Application.StartupPath + "\\config.xml");

        }

        private void SetupForm_Resize(object sender, EventArgs e)
        {
            btn_save.Left = this.Width - 236;
            btn_save.Top = this.Height - 82;
        }
    }
    public class Config
    {

        [CategoryAttribute("1.FTP Config")]
        [DescriptionAttribute("您的FTP服务器的地址，比如 ftp.miuser.net")]
        public string ServerAddress { get; set; }
        [CategoryAttribute("1.FTP Config")]
        [DescriptionAttribute("登录您的FTP服务器的用户名，比如 miuser")]
        public string UserName { get; set; }
        [CategoryAttribute("1.FTP Config")]
        [DescriptionAttribute("对应用户名的FTP服务器的密码，比如 *****")]
        public string Password { get; set; }
        [CategoryAttribute("1.FTP Config")]
        [DescriptionAttribute("FTP服务器的端口号，一般默认是21")]
        public int Port { get; set; }
        [CategoryAttribute("1.FTP Config")]
        
        public string HttpUrlHead { get; set; }
        [CategoryAttribute("1.FTP Config")]


        public int SavetoFile(String filename)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Config));
                TextWriter writer = new StreamWriter(filename);
                serializer.Serialize(writer, this);
                writer.Close();
            }

            catch (Exception ee)
            {
                MessageBox.Show(ee.StackTrace, ee.Message);
                return 0;
            }

            return 1;
        }
        public static Config LoadfromFile(String filename)
        {
            try
            {
                Config sptr;
                XmlSerializer serializer = new XmlSerializer(typeof(Config));
                TextReader reader = new StreamReader(filename);
                sptr = (Config)(serializer.Deserialize(reader));
                reader.Close();
                return sptr;

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.StackTrace, ee.Message);
                return null;
            }

        }

    }

}
